package com.xxx;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 一元通信方式 单个请求参数 FutureStub代理方式
 * FutureStub 支持同步和异步 但是只能进行一元通信方式
 */
public class GrpcClient7 {

    public static void main(String[] args) {
        // 1.创建通信的管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();
        try {
            // 2.获取代理对象 stub
            FutureStubTestServiceGrpc.FutureStubTestServiceFutureStub futureStubTestServiceFutureStub = FutureStubTestServiceGrpc.newFutureStub(managedChannel);
            // 3.完成RPC调用
            ListenableFuture<FutureStubTestProto.FutureStubTestResponse> responseListenableFuture = futureStubTestServiceFutureStub.testxxx(FutureStubTestProto.FutureStubTestRequest.newBuilder().setName("future stub xxx").build());

            // 同步方式调用
            // FutureStubTestProto.FutureStubTestResponse futureStubTestResponse = responseListenableFuture.get();
            // System.out.println(futureStubTestResponse.getResult());

            // 异步方式无法用于实战，因为拿不到响应结果
            // responseListenableFuture.addListener(new Runnable() {
            //     @Override
            //     public void run() {
            //         System.out.println("异步调用返回结果了");
            //     }
            // }, Executors.newCachedThreadPool());

            // 异步方式可用于实战，因为能拿到响应结果
            Futures.addCallback(responseListenableFuture, new FutureCallback<FutureStubTestProto.FutureStubTestResponse>() {
                @Override
                public void onSuccess(FutureStubTestProto.FutureStubTestResponse result) {
                    System.out.println("server端返回响应: " + result.getResult());
                }

                @Override
                public void onFailure(Throwable t) {

                }
            }, Executors.newCachedThreadPool());

            System.out.println("请求发送完成后的后续操作......");
            // 异步方式需要等待处理
            managedChannel.awaitTermination(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            // 关闭通道
            managedChannel.shutdown();
        }
    }
}
